package com.springboot.config.controller;

import com.auth0.jwt.JWT;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author zyj
 * @description
 * @date 2019/3/25 20:00
 **/
public abstract class BaseController {

    public HttpServletResponse getResponse(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getResponse();
    }

    public HttpServletRequest getRequest(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }

    public HttpSession getSession(){
        return getRequest().getSession(true);
    }

    public Object getSessionValue(String key){
        HttpSession session = getRequest().getSession(true);
        return getSession().getAttribute(key);
    }


    public String getUserId(){
        String token = getRequest().getHeader("token");
        if(StringUtils.isEmpty(token)){
            return null;
        }
        return JWT.decode(token).getAudience().get(0);
    }

    public String getUrlName(){
        HttpServletRequest request = getRequest();
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
    }

    public String getToken(){
        String token = getRequest().getHeader("token");
        return token;
    }
}
